package com.cx.utils.hessian;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.remoting.caucho.HessianServiceExporter;

import com.cx.mapper.impl.BaseMapperImpl;
import com.cx.utils.ConfigUtil;

/**
 * 
  * @ClassName(类名)      : WolfHessianServiceExporter
  * @Description(描述)    : 代替HessianServiceExporter（原生）
  * @author(作者)         ：曹轩
  * @date (开发日期)      ：2015年9月29日 下午3:07:01
  *
 */
public class WolfHessianServiceExporter extends HessianServiceExporter{
	//日志
	private static Logger log = Logger.getLogger(BaseMapperImpl.class);
	@Override
	public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//客户端的IP地址
		String client_ip = getIp(request);
		log.debug("客户端Ip地址:"+client_ip);
		
		//获取配置文件允许访问的IP地址
        List<String> allow_ips = ConfigUtil.getList("allow_ip");
        if (allow_ips.contains(client_ip)) {
            super.handleRequest(request, response);
        } else {
            throw new ServletException("非法请求" + client_ip);
        }
	}

	/**
	 * 
	 * @Description(功能描述)    :  获取客户端Ip
	 * @author(作者)             ：  曹轩
	 * @date (开发日期)          :  2015年9月29日 下午3:09:10 
	 * @exception                : 
	 * @param request
	 * @return  String
	 */
	private String getIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
            ip = request.getHeader(" Proxy-Client-IP ");
        }
        if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
            ip = request.getHeader(" WL-Proxy-Client-IP ");
        }
        if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
		return ip;
	}
}
